import axios from "axios";
import NProgress from "nprogress";
import { ElMessage } from "element-plus";

const service = axios.create({
  timeout: 20 * 10e3,
  headers: {
    "Content-Type": "application/json;charset=UTF-8;",
  },
});

// 正在请求的数量
let requestCount = 0;

const showProgress = () => {
  if (requestCount === 0) {
    NProgress.start();
    NProgress.inc();
  }

  requestCount++;
};

const hideProgress = () => {
  requestCount--;
  if (requestCount === 0) {
    NProgress.done();
  }
};

service.interceptors.request.use(
  (config) => {
    showProgress();

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    hideProgress();
    if (response.data.result_code === 0) {
      return response.data.result;
    } else {
      ElMessage.error(response.data.msg);
    }
    return response.data;
  },
  (error) => {
    if (error.response && error.response.status) {
      const status = error.response.status;
      console.log(status);
      ElMessage.error("服务错误");
      return Promise.reject(error);
    }
    return Promise.reject(error);
  }
);

export default (function () {
  return {
    GET: function (url, params = {}, options) {
      return service.get(url, { params, ...options });
    },
    POST: function (url, params = {}, options) {
      return service.post(url, params, options);
    },
  };
})(this);
